package com.kyrie.lib_sys.application.timeApplys.service.impl;

import com.kyrie.lib_sys.application.timeApplys.pojo.dto.TimeListDTO;
import com.kyrie.lib_sys.application.timeApplys.pojo.entity.TimeList;
import com.kyrie.lib_sys.application.timeApplys.mapper.TimeListMapper;
import com.kyrie.lib_sys.application.timeApplys.service.TimeListService;
import com.kyrie.lib_sys.utils.learn.TimeDemo.TimeOverlapValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
public class TimeListServiceImpl implements TimeListService {

    @Autowired
    private TimeListMapper timeListMapper;


    /**
     * 校验时间列表
     * @param timeListDTO
     */
    @Override
    public void validateTimeList(TimeListDTO timeListDTO) {

        Map<String, String> map = new HashMap<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        if (timeListDTO.getPrepareTime() != null) {
            map.put("prepareTime", timeListDTO.getPrepareTime().format(formatter));
        }
        if (timeListDTO.getTravelTime() != null) {
            map.put("travelTime", timeListDTO.getTravelTime().format(formatter));
        }
        if (timeListDTO.getStartTime() != null) {
            map.put("startTime", timeListDTO.getStartTime().format(formatter));
        }
        if (timeListDTO.getCompleteTime() != null) {
            map.put("completeTime", timeListDTO.getCompleteTime().format(formatter));
        }
        if (timeListDTO.getEmployeeId() != null) {
            map.put("pk_psndoc", timeListDTO.getEmployeeId().toString());
        }

        // 封装成一个 List<Map>（虽然只有一个）
        List<Map<String, String>> mapList = new ArrayList<>();
        mapList.add(map);

        // 调用校验工具
        boolean result = TimeOverlapValidator.validate(mapList);
        if (!result) {
            throw new RuntimeException("时间顺序或时间重叠校验未通过");
        }

    }

    /**
     * 校验时间列表(dto集合) 并保存
     * @param timeListDTO
     */
    @Override
    public void validateList(List<TimeListDTO> timeListDTO) {
        List<Map<String, String>> newTimeList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 遍历当前的dto,将dto转换成Map
        for (TimeListDTO dto : timeListDTO) {
            newTimeList.add(convertDtoToMap(dto, formatter));
        }

        // 校验当前录入时间内部是否有重叠或顺序错误
        if (!TimeOverlapValidator.validate(newTimeList)) {
            throw new RuntimeException("时间顺序或时间重叠校验未通过");
        }

        // 查询历史数据
        // 获取列表中第一个TimeListDTO对象的员工ID
        // 注意：这里假设列表至少有一个元素，实际使用时需要确保非空
        Long empId = timeListDTO.get(0).getEmployeeId();
        List<TimeList> empTimeList = timeListMapper.findByEmployeeId(empId);

        if (empTimeList.isEmpty()) {
            log.info("该员工没有历史数据，仅进行当前时间段校验");
            timeListMapper.insertBatch(newTimeList);
            return;
        }

        //遍历数据库中的entity,entity转成Map
        List<Map<String, String>> oldTimeList = new ArrayList<>();
        for (TimeList dto : empTimeList) {
            oldTimeList.add(convertEntityToMap(dto, formatter));
        }


        // 合并当前录入和历史时间，一起校验
        List<Map<String, String>> mergedList = new ArrayList<>(oldTimeList);
        mergedList.addAll(newTimeList);

        if (!TimeOverlapValidator.validate(mergedList)) {
            throw new RuntimeException("当前录入的工时与历史工时存在重叠冲突");
        }

        // 所有校验通过，保存新数据
        timeListMapper.insertBatch(newTimeList);
    }


    // 提取共用方法
    private Map<String, String> convertDtoToMap(TimeListDTO dto, DateTimeFormatter formatter) {
        Map<String, String> map = new HashMap<>();
        if (dto.getEmployeeId() != null) {
            map.put("employeeId", dto.getEmployeeId().toString());
        }
        if (dto.getPrepareTime() != null) {
            map.put("prepareTime", dto.getPrepareTime().format(formatter));
        }
        if (dto.getTravelTime() != null) {
            map.put("travelTime", dto.getTravelTime().format(formatter));
        }
        if (dto.getStartTime() != null) {
            map.put("startTime", dto.getStartTime().format(formatter));
        }
        if (dto.getCompleteTime() != null) {
            map.put("completeTime", dto.getCompleteTime().format(formatter));
        }
        return map;
    }

    private Map<String, String> convertEntityToMap(TimeList dto, DateTimeFormatter formatter) {
        Map<String, String> map = new HashMap<>();
        if (dto.getEmployeeId() != null) {
            map.put("employeeId", dto.getEmployeeId().toString());
        }
        if (dto.getPrepareTime() != null) {
            map.put("prepareTime", dto.getPrepareTime().format(formatter));
        }
        if (dto.getTravelTime() != null) {
            map.put("travelTime", dto.getTravelTime().format(formatter));
        }
        if (dto.getStartTime() != null) {
            map.put("startTime", dto.getStartTime().format(formatter));
        }
        if (dto.getCompleteTime() != null) {
            map.put("completeTime", dto.getCompleteTime().format(formatter));
        }
        return map;
    }




}
